import java.io.File;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.io.FilenameFilter;

interface Callback {

	void callback();// would be in any signature
}

public class SaveWorkRoutine implements Runnable {

	// Callback implementation
	Callback c;

	ArrayList<FileObject> filesToSend;

	/* Constructor */
	public SaveWorkRoutine(Callback c) {
		this.filesToSend = new ArrayList<FileObject>();
		this.c = c;
	}

	/* Main routine */
	public void run() {

		// DEBUG
		System.out.println("Working directory : ");
		System.out.println(PrefProperties.workingDirectory);

		// Initiate the working dir and the filter
		File dir = new File(PrefProperties.workingDirectory);
		FilenameFilter extension = FileOperation.withExtension("odt", "doc");
		
		// List all dir
		List<File> allFiles = FileOperation.listDir(dir, extension);

		// DEBUG
		System.out.println("Files founded : ");
		for (File file : allFiles) {
			System.out.println(file);
		}

		// DEBUG
		DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

		// For all the folder in the directory
		for (File toSerializeFilePath : allFiles) {

			Date lastModified = new Date(toSerializeFilePath.lastModified());

			// DEBUG
			System.out.println("Compare : " + df.format(lastModified)
					+ " with : " + df.format(PrefProperties.lastSave));

			// Check if the file was created after the last file save operation
			if (lastModified.compareTo(PrefProperties.lastSave) > 0) {

				// ---------------------------------------------------
				// Serialization and encryption
				FileObject toSerializeFile = new FileObject(null, 0,
						toSerializeFilePath.getAbsolutePath());
				File serializedFile = FileOperation
						.serializeFile(toSerializeFile);
				File serializedAndEncryptedFile = FileOperation.encrytpFile(
						serializedFile, PrefProperties.password);

				// DEBUG
				System.out.println("File : "
						+ serializedAndEncryptedFile.getName()
						+ " will be saved.");

				// ---------------------------------------------------
				// Move file to "to-send" directory
				try {
					String toSendPath = PrefProperties.workingDirectory
							+ "/.to-send/" + toSerializeFile.patientID + "-"
							+ serializedAndEncryptedFile.getName();
					if (serializedAndEncryptedFile
							.renameTo(new File(toSendPath))) {
						toSerializeFile.toSendPath = toSendPath;
						filesToSend.add(toSerializeFile);
					} else {
						System.out.println("File failed to move!");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		this.c.callback();// callback
	}

	public ArrayList<FileObject> getFilesToSend() {

		return filesToSend;
	}

}
